// packageA/pages/testPage/testPage.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    select: '3',
    questionList: [],
    userName: '',
    userTel: '',
    resultList: [],
    userId: "",
    radio: '3',
    isChooseOther: false, //测他人
    isChooseFrom: false, //  从通讯录选择
    hisList: [],
    hobby: [
      {
        name: '他人',
        value: '3',
        checked: 'false'
      },
      {
        name: '通过通讯录选他人',
        value: '2',
        checked: 'false'
      },
    ]
  },

  getQuesTion() {
    wx.showLoading({
      title: '',
      icon: 'none'
    })
    var that = this
    var url = app.globalData.url + "nine/testOthers";
    app.wxRequest(url, {}, res => {
      if (res.flag) {
        console.log(res);
        var datas = res.data,
          list = [];
        datas.forEach(ele => {
          console.log(ele);
          var q = ele.questionsContent.split('@');
          var r = ele.enneagrams.split('@');
          console.log(q);
          ele.arr = [{
            question: q[0],
            ren: r[0],
            isCheck: false
          },
          {
            question: q[1],
            ren: r[1],
            isCheck: false
          }
          ]
          list.push(ele.arr)
        })
        console.log(list);
        that.setData({
          questionList: list
        })
        that.getHis()
        wx.hideLoading()
      }
    })

  },

  inputHandle(e) {
    console.log(e);
    var str = e.currentTarget.dataset.flag
    console.log(str);
    var val = e.detail.value
    this.setData({
      [str]: val
    })
    console.log(this.data);
  },
  onChange(e) {
    console.log(e);
    var that = this;
    if (e.detail.value == '2') {
      ks.chooseContact({
        success: function (res) {
          console.log(res);
          userName = res.displayName
          console.log(res, '成功回调')
          that.setData({
            userName: userName,
            userTel: res.phoneNumber
          })
        },
        fail(res) {
          console.log(res, '错误回调')
        },
        complete(res) {
          console.log(res, '结束回调')
        }
      })

    }
    if (e.detail.value == '') {
      userName = "";
      that.setData({
        userName: userName
      })
    }
    this.setData({
      select: e.detail.value,
    })
    console.log(this.data.select)
  },

  selectQuesHandle(e) {
    var index = e.currentTarget.dataset.index,
      eindex = e.currentTarget.dataset.eindex,
      list = this.data.questionList,
      hisList = this.data.hisList
    list[index].forEach((ele, I) => {
      if (eindex == I) {
        ele.isCheck = !ele.isCheck
      } else {
        ele.isCheck = false
      }
    })
    if (!hisList.some(item => {
      return item.qIndex == index
    })) {
      hisList.push({
        qIndex: index,
        itemIndex: eindex
      })
    } else {
      hisList.forEach(ele => {
        if (ele.qIndex == index) {
          ele.itemIndex = eindex
        }
      })
    }
    wx.setStorageSync('testOtherHis', JSON.stringify(hisList))

    this.setData({
      questionList: list
    })
  },
  getHis() {
    if (wx.getStorageSync('testOtherHis') == '') {
      return
    }
    var his = JSON.parse(wx.getStorageSync('testOtherHis'))
    this.setData({
      hisList: his
    })
    console.log(his);
    // return
    var ques = this.data.questionList
    console.log(ques);
    his.forEach(ele => {
      console.log(ele);
      ques[ele.qIndex][ele.itemIndex].isCheck = true
    })
    this.setData({
      questionList: ques
    })
  },

  // 提交
  submitHandle() {
    if (this.data.select == '3') {
      if (this.data.userName == '' || this.data.userTel == '' || !this.validator(this.data.userTel)) {
        wx.showToast({
          title: '请输入姓名或手机号或您输入的手机号有误',
          icon: 'none'
        })
        return

      }
    }

    var list = this.data.questionList,
      indexs = ''
    list.forEach((item, index) => {
      if (item.every(ele => {
        return !ele.isCheck
      })) {
        indexs += index + 1 + ','
      }
    })
    console.log(indexs);

    if (indexs !== '') {
      wx.showToast({
        title: `第${indexs}题未作答`,
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '提交中',
      icon: 'none'
    })
    var typeList = [{
      type: 1,
      num: 0,
      text: '完美型'
    },
    {
      type: 2,
      num: 0,
      text: '全爱型'
    },
    {
      type: 3,
      num: 0,
      text: '成就型'
    },
    {
      type: 4,
      num: 0,
      text: '艺术型'
    },
    {
      type: 5,
      num: 0,
      text: '智慧型'
    },
    {
      type: 6,
      num: 0,
      text: '忠诚型'
    },
    {
      type: 7,
      num: 0,
      text: '活跃型'
    },
    {
      type: 8,
      num: 0,
      text: '领袖型'
    },
    {
      type: 9,
      num: 0,
      text: '和平型'
    },
    ]
    list.forEach((ele, index) => {
      ele.forEach(item => {
        if (item.isCheck) {
          typeList.forEach(tItem => {
            var results = item.ren.split(",");
            for (var i in results) {
              if (results[i] == tItem.type) {
                tItem.num++
              }
            }


          })
        }
      })
    })
    typeList = typeList.sort((a, b) => {
      return b.num - a.num
    })

    console.log(typeList);

    var that = this
    var url = app.globalData.url + "nine/addTestResult";
    app.wxRequest(url, {
      flag: that.data.select,
      userName: that.data.userName,
      userTel: that.data.userTel,
      resultNumber: typeList[0].type,
      userId: that.data.userId,

    }, res => {
      console.log(res);
      if (res.flag) {
        res.data.flagss = 1;
        var obj = {
          userName: that.data.userName,
          userTel: that.data.userTel,
          resultList: typeList,
          result: res.data
        }
        wx.removeStorage({
          key: 'testOtherHis',
        })
        wx.hideLoading();
        wx.redirectTo({
          url: '/packageB/pages/testResult/testResult?obj=' + JSON.stringify(obj),
        })
      }
    })

  },

  // 验证手机号 和座机号
  validator: function (val) {
    return /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/.test(val) || /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/.test(val);
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      userId: app.globalData.userId
    })
    this.getQuesTion()
    // this.getIndex()
  },
  getIndex() {
    wx.showLoading({
      title: '加载中...',
    })
    var that = this;
    console.log(this.data.userInfo);
    var url = app.globalData.url + "nine/getIndex";
    app.wxRequest(url, {
      userId: app.globalData.userId
    }, res => {
      console.log(app.globalData.userInfo);
      console.log(res);
      wx.hideLoading();
      if (res.flag) {
        app.globalData.isPay = res.data.flag
      }
    }, err => {

    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getQuesTion()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})